﻿

namespace Peer.Web.UI.WebControls
{
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class WebCalendar : TextBox
    {
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.MaxLength = this.IsContainTime ? 0x13 : 10;
            base.Attributes.Add("size", this.MaxLength.ToString());
            
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            string webResourceUrl = this.Page.ClientScript.GetWebResourceUrl(base.GetType(),WebRes.CalendarDrop_gif);
            string str2 = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), WebRes.CalendarDrop1_gif);
            writer.Write(string.Format("<img border='0' src={0} onclick='new Calendar(null, null, 0).show(document.getElementById({1}));' onmouseover='this.src={2}' onmouseout='this.src={0}'>", "\"" + webResourceUrl + "\"", "\"" + this.ClientID + "\"", "\"" + str2 + "\""));
        }

        protected override object SaveViewState()
        {
            string webResourceUrl = this.Page.ClientScript.GetWebResourceUrl(base.GetType(),WebRes.Calendar_Js);
            LiteralControl child = new LiteralControl();
            child.Text = string.Format("<script language='javascript' type='text/javascript' src='{0}'></script>", webResourceUrl);
            this.Page.Controls.Add(child);
            return base.SaveViewState();
        }

        public bool IsContainTime
        {
            get
            {
                if (this.ViewState[this.UniqueID + ":IsContainTime"] == null)
                {
                    return false;
                }
                return (bool)this.ViewState[this.UniqueID + ":IsContainTime"];
            }
            set
            {
                this.ViewState[this.UniqueID + ":IsContainTime"] = value;
            }
        }

        public DateTime? Value
        {
            get
            {
                DateTime time;
                if (DateTime.TryParse(this.Text, out time))
                {
                    return new DateTime?(time);
                }
                return null;
            }
            set
            {
                if (!value.HasValue)
                {
                    this.Text = "";
                }
                else
                {
                    string format = this.IsContainTime ? "yyyy-MM-dd hh:mm:ss" : "yyyy-MM-dd";
                    this.Text = value.Value.ToString(format);
                }
            }
        }
    }
}

